import tkinter as tk
from tkinter import scrolledtext, messagebox, ttk
import socket
import threading

class ClientGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("Socket客户端")
        self.root.geometry("600x500")
        
        # 客户端状态
        self.client_socket = None
        self.connected = False
        self.receiving = False
        
        # 创建界面
        self.create_widgets()
        
    def create_widgets(self):
        # 连接控制区域
        control_frame = ttk.Frame(self.root)
        control_frame.pack(fill=tk.X, padx=10, pady=5)
        
        ttk.Label(control_frame, text="主机:").pack(side=tk.LEFT)
        self.host_entry = ttk.Entry(control_frame, width=15)
        self.host_entry.insert(0, socket.gethostname())
        self.host_entry.pack(side=tk.LEFT, padx=(5, 5))
        
        ttk.Label(control_frame, text="端口:").pack(side=tk.LEFT)
        self.port_entry = ttk.Entry(control_frame, width=10)
        self.port_entry.insert(0, "12345")
        self.port_entry.pack(side=tk.LEFT, padx=(5, 10))
        
        self.connect_button = ttk.Button(control_frame, text="连接服务器", command=self.connect_to_server)
        self.connect_button.pack(side=tk.LEFT, padx=(0, 5))
        
        self.disconnect_button = ttk.Button(control_frame, text="断开连接", command=self.disconnect_from_server, state=tk.DISABLED)
        self.disconnect_button.pack(side=tk.LEFT, padx=(0, 5))
        
        self.status_label = ttk.Label(control_frame, text="客户端状态: 未连接")
        self.status_label.pack(side=tk.RIGHT)
        
        # 消息发送区域
        send_frame = ttk.LabelFrame(self.root, text="发送消息到服务器")
        send_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.message_entry = ttk.Entry(send_frame, width=50)
        self.message_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=5)
        self.message_entry.bind("<Return>", self.send_message)
        self.message_entry.config(state=tk.DISABLED)
        
        self.send_button = ttk.Button(send_frame, text="发送", command=self.send_message, state=tk.DISABLED)
        self.send_button.pack(side=tk.RIGHT, padx=5, pady=5)
        
        # 消息显示区域
        log_frame = ttk.LabelFrame(self.root, text="消息日志")
        log_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        self.log_text = scrolledtext.ScrolledText(log_frame, height=20, state=tk.DISABLED)
        self.log_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
    def connect_to_server(self):
        try:
            host = self.host_entry.get()
            port = int(self.port_entry.get())
            
            # 创建socket并连接
            self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.client_socket.connect((host, port))
            self.connected = True
            
            # 更新界面状态
            self.connect_button.config(state=tk.DISABLED)
            self.disconnect_button.config(state=tk.NORMAL)
            self.message_entry.config(state=tk.NORMAL)
            self.send_button.config(state=tk.NORMAL)
            self.status_label.config(text=f"客户端状态: 已连接 ({host}:{port})")
            self.log_message(f"已连接到服务器 {host}:{port}")
            
            # 启动接收消息线程
            self.receiving = True
            self.receive_thread = threading.Thread(target=self.receive_messages, daemon=True)
            self.receive_thread.start()
            
        except Exception as e:
            messagebox.showerror("连接错误", f"无法连接到服务器: {str(e)}")
            
    def disconnect_from_server(self):
        self.receiving = False
        self.connected = False
        
        if self.client_socket:
            try:
                self.client_socket.close()
            except:
                pass
            self.client_socket = None
            
        # 更新界面状态
        self.connect_button.config(state=tk.NORMAL)
        self.disconnect_button.config(state=tk.DISABLED)
        self.message_entry.config(state=tk.DISABLED)
        self.send_button.config(state=tk.DISABLED)
        self.status_label.config(text="客户端状态: 未连接")
        self.log_message("已断开与服务器的连接")
        
    def receive_messages(self):
        while self.receiving and self.client_socket:
            try:
                # 设置接收超时，以便能及时响应断开连接
                self.client_socket.settimeout(1.0)
                data = self.client_socket.recv(1024)
                if data:
                    message = data.decode('utf-8')
                    self.root.after(0, lambda: self.log_message(f"接收: {message}"))
                else:
                    # 服务器关闭连接
                    self.root.after(0, self.on_server_disconnect)
                    break
            except socket.timeout:
                # 超时继续循环
                continue
            except Exception as e:
                if self.receiving:
                    self.root.after(0, lambda: self.log_message(f"接收消息时出错: {str(e)}"))
                    self.root.after(0, self.on_server_disconnect)
                break
                
    def on_server_disconnect(self):
        self.receiving = False
        self.connected = False
        
        if self.client_socket:
            try:
                self.client_socket.close()
            except:
                pass
            self.client_socket = None
            
        # 更新界面状态
        self.connect_button.config(state=tk.NORMAL)
        self.disconnect_button.config(state=tk.DISABLED)
        self.message_entry.config(state=tk.DISABLED)
        self.send_button.config(state=tk.DISABLED)
        self.status_label.config(text="客户端状态: 未连接")
        self.log_message("与服务器的连接已断开")
        
    def send_message(self, event=None):
        if not self.connected or not self.client_socket:
            messagebox.showwarning("警告", "未连接到服务器")
            return
            
        message = self.message_entry.get()
        if not message:
            messagebox.showwarning("警告", "请输入要发送的消息")
            return
            
        try:
            self.client_socket.send(message.encode('utf-8'))
            self.log_message(f"发送: {message}")
            self.message_entry.delete(0, tk.END)
        except Exception as e:
            messagebox.showerror("发送错误", f"发送消息失败: {str(e)}")
            self.on_server_disconnect()
            
    def log_message(self, message):
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, f"{message}\n")
        self.log_text.see(tk.END)
        self.log_text.config(state=tk.DISABLED)

# 原始客户端代码保持不变
class OriginalClient:
    def __init__(self):
        self.s = socket.socket()
        self.host = socket.gethostname()
        self.port = 12345
        
    def run(self):
        self.s.connect((self.host, self.port))
        print(self.s.recv(1024).decode('utf-8'))
        self.s.close()

if __name__ == "__main__":
    root = tk.Tk()
    app = ClientGUI(root)
    root.mainloop()